<template>
  <el-card shadow="never"
           class="aui-card--fill">
    <div>
      <div class="control-section">
        <div class="content-wrapper"
             v-loading="loading">
          <ejs-grid
            :style="{ height: gadgetHeight-60 + 'px' }"
            :dataSource="comDataList"
            :allowResizing="gridDefaultSetting.allowResizing"
            :allowFiltering="gridDefaultSetting.allowFiltering"
            :filterSettings="gridDefaultSetting.filterSettings"
            :allowGrouping="gridDefaultSetting.allowGrouping"
            :allowPaging="gridDefaultSetting.allowPaging"
            :height="gadgetHeight - 250"
            :toolbar="gridDefaultSetting.toolbar"
            :allowTextWrap="gridDefaultSetting.allowTextWrap"
            :showColumnChooser="gridDefaultSetting.showColumnChooser"
            :allowReordering="gridDefaultSetting.allowReordering"
            :allowSorting="gridDefaultSetting.allowSorting"
            :load="load"
            :dataBound="dataBound"
            :pageSettings="gridDefaultSetting.pageSettings"
            ref="crudgrid"
            :editSettings="editSettings"
            :showColumnMenu='gridDefaultSetting.showColumnMenu'
            :toolbarClick='toolbarClick'
            :allowExcelExport='gridDefaultSetting.allowExcelExport'
            :allowPdfExport='gridDefaultSetting.allowPdfExport'
            :actionComplete='actionComplete'
          >
          </ejs-grid>
          <model
                 :showSetting="queryModelDefaultSetting.showSetting"
                 @queryModelClosed="queryModelClosed"
                 @queryModelPreview="queryModelPreview"
                 :dataInfo="queryModelDefaultSetting.dataInfo"
                 :updateGadget="upgradeGadgetSetting"
                 :mappingForm="mappingFormSetting"
                 @saveGadgetSetting='saveGadgetSetting'
                 :slicer="slicer"/>

        </div>
      </div>
    </div>
  </el-card>
</template>

<script>

import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import mixinViewModule from '@/mixins/simplereport-view-module'

export default {
  mixins: [mixinGadgetViewModule, mixinViewModule],
  components: { model: () => import('@/components/gadget/query-model/query-model') },
  data () {
    return {
      loading: false,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetSettingExclude: ['DATA'],
          gadgetType: 'crudgadget',
          gadgetSetting: {
            getDataListApi: `/web/nt/next-ticket/${this.$store.state.user.tenantCode}/grading`,
            getDataInfoApi: '',
            addDataInfoApi: '',
            updateDataInfoApi: '/web/reports/sys/report/',
            deleteDataInfoApi: '',
            report: {}
          }
        }
      },
      commandsList: [
        {
          type: 'Edit',
          buttonOption: {
            content: this.$t('custom.reports.editbtn'),
            cssClass: 'e-outline e-small e-primary'
          }
        },
        {
          type: 'Delete',
          buttonOption: {
            content: this.$t('custom.reports.deletebtn'),
            cssClass: 'e-outline e-small e-danger'
          }
        },
        {
          type: 'Update',
          buttonOption: {
            content: 'Update',
            cssClass: 'e-outline e-small e-success'
          }
        }
      ],
      editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Dialog' },
      dataList: [],
      dataForm: {},
      heightoffset: 60,
      isGridInit: false
    }
  },

  computed: {
    comDataList () {
      var _self = this
      var retdata = _self.dataList
      return retdata
    }
  },
  created () {
    this.subscribeMessage('runReport', this.query)
  },
  watch: {
    editMode (val) {
      if (!val) {
        this.saveGadgetSetting()
      }
    }
  },
  methods: {
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query(true)
    },
    queryModelPreview () {
      this.query(true)
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 15
      this.gadgetWidth = newWPx
    },
    load (item) {
      this.grid = this.$refs.crudgrid
      this.gadgetHeight = this.gadgetInfo.h * 20 - 15
    },
    toolbarClick (args) {
      switch (args.item.text) {
        case 'PDF Export':
          (this.$refs['datagrid']).pdfExport()
          break
        case 'Excel Export':
          (this.$refs['datagrid']).excelExport()
          break
        case 'CSV Export':
          (this.$refs['datagrid']).csvExport()
          break
      }
    },
    commandClick (e) {
      if (e.commandColumn.type === 'Edit') {
        this.addOrUpdateHandle(e.rowData.id)
      }
      if (e.commandColumn.type === 'Delete') {
        this.deleteHandle(e.rowData.id)
      }
      if (e.commandColumn.type === 'Update') {
        this.updateHandle(e.rowData)
      }
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    actionComplete (args) {
      if (args.requestType === 'save') {
        this.addOrUpdateHandle(args.data)
      }
    },
    actionBegin (args) {
    },
    applyGadgetSetting () {
      let columnsList = []
      let isAutofit = false
      // :multiline="true"
      // process link column
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        const element = this.gadgetSetting.report.columns[index]
        columnsList.push(element.field)
        if (this.gadgetSetting.report.columns[0] && !this.gadgetSetting.report.columns[0].width) {
          isAutofit = true
        }
      }
      if (isAutofit) {
        this.$refs.crudgrid.autoFitColumns(columnsList)
      }
      this.grid.ej2Instances.setProperties(this.gadgetSetting.report)
    },
    saveGadgetSetting () {
      var _self = this
      var report = JSON.parse(this.grid.ej2Instances.getPersistData())
      this._.merge(_self.gadgetSetting.report, report)
      delete _self.gadgetSetting.report
      // grid table , save obj  from json obj
      const params = {
        gadgetSetting: {
          report: report
        },
        gadgetId: this.id
      }
      this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
      })
    },
    query () {
      this.loading = true
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      var _self = this
      var param = {
        ...this.slicer,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        // _self.verifyHasData(res)
        if (res.config) {
          _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
        }
        if (_self.gadgetSetting.getDataListApi) {
          this.getDataList()
        }
        this.heightoffset = 5
        _self.gadgetHeight = (_self.gadgetInfo.h * 20) - _self.heightoffset - 15

        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getDataList () {
      var _self = this
      var param = {
        ...this.slicer,
        clientCode: this.$store.state.user.tenantCode
      }
      this.$interface.nextTicket.getNtGradingDataListAPI(param).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data) {
          _self.dataList = res.data
          _self.$refs.crudgrid.dataSource = _self.dataList
        }
        _self.isGridInit = false
      }).catch(() => {
      })
    },
    addOrUpdateHandle (data) {
      var _self = this
      if (_self.gadgetSetting.updateDataInfoApi) {
        var param = {
          ...data
        }
        _self.gadgetSetting.updateDataInfoApi = _self.gadgetSetting.updateDataInfoApi + param.id + '/update'
        this.$interface.app.updateDataInfoApi(_self.gadgetSetting.updateDataInfoApi, param).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.query()
          return this.$message.success(res.msg)
        }).catch(() => {

        })
      }
    },
    deleteHandle () {
      var _self = this
      var param = {}
      this.$interface.app[_self.gadgetSetting.deleteDataInfoApi](param).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
      }).catch(() => {

      })
    },
    updateHandle () {

    }

  }

}
</script>

<style>

</style>
